package com.example.text

import android.content.Context
import android.os.SystemClock
import android.util.TypedValue
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.text.app.App
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import me.jessyan.autosize.utils.AutoSizeUtils

fun <T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState: Lifecycle.State = Lifecycle.State.RESUMED,
    action:suspend (T) -> Unit
): Job = lifecycleOwner.lifecycleScope.launch {
    lifecycleOwner.repeatOnLifecycle(minState){
        collectLatest {
            action.invoke(it)
        }
    }
}

//获取属性值
fun getAttrValue(context: Context, attrId: Int): Int {
    val typedValue = TypedValue()
    context.theme.resolveAttribute(attrId, typedValue, true)
    return typedValue.resourceId
}

val appContext: Context
    get() = App.getAppContext()

//dp转px 按照dp单位绘制，根据手机dpi屏幕像素密码绘制对应px
val Int.dp: Int
    get() = AutoSizeUtils.dp2px(appContext, this.toFloat())

//按键消抖
fun View.clickFlow() = callbackFlow {
    setOnClickListener {
        trySend(Unit).onFailure { e -> e?.printStackTrace() }
    }
    awaitClose { setOnClickListener(null) }
}

fun <T> Flow<T>.throttleFirst(thresholdMillis: Long) = flow {
    var lastTime = 0L
    collect { upstream ->
        val currentTime = SystemClock.elapsedRealtime()
        if (currentTime - lastTime >= thresholdMillis) {
            lastTime = currentTime
            emit(upstream)
        }
    }
}


